package com.zhongwang.business.module.invoiceManage.service;

import com.zhongwang.business.base.BaseService;
import com.zhongwang.business.gen.entity.User;
import com.zhongwang.business.module.fileManage.dao.FileDao;
import com.zhongwang.business.module.fileManage.model.FileModel;
import com.zhongwang.business.module.invoiceManage.dao.InvoiceListDao;
import com.zhongwang.business.module.invoiceManage.model.InvoiceInfo;
import com.zhongwang.business.module.invoiceManage.model.InvoiceListModel;
import com.zhongwang.business.util.FileUtils;
import com.zhongwang.business.util.ShiroUtils;
import com.zhongwang.business.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Service
public class InvoiceListService extends BaseService {

    @Autowired
    private InvoiceListDao invoiceListDao;


    @Value("${user.upload.path}")
    private String uploadPath;


    @Autowired
    private FileDao fileDao;


    /**
     * 款票列表  赵晨博
     *
     * @param model
     * @return
     */
    public List<InvoiceListModel> invoiceListModelList(InvoiceListModel model) {
        List<InvoiceListModel> list;
        User u = ShiroUtils.getUser();
//        int orderNo = invoiceListDao.selectUserLevelByUserId(u.getId());
//        if (orderNo >= 4) {
//            list = invoiceListDao.invoiceList1(model);
//        } else {
        String loginUName = u.getName();
        model.setLoginUName(loginUName);
        list = invoiceListDao.invoiceList3(model);
//        }
        int m = list.size();
        for (int i = 0; i < m; i++) {
            List<InvoiceListModel> subList = invoiceListDao.selectProjecByConId(list.get(i).getConId());
            /**
             * 循环项目名称
             */
            String name = "";
            for (int k = 0; k < subList.size(); k++) {
                name = name + subList.get(k).getName() + "；</br>";
            }
            list.get(i).setName(name);
        }
        return list;
    }


    /**
     * 款票查询  赵晨博
     *
     * @param model
     * @return
     */
    public List<InvoiceListModel> invoiceListModelList4(InvoiceListModel model) {
        List<InvoiceListModel> list;
        list = invoiceListDao.invoiceList1(model);
        int m = list.size();
        for (int i = 0; i < m; i++) {
            List<InvoiceListModel> subList = invoiceListDao.selectProjecByConId(list.get(i).getConId());
            /**
             * 循环项目名称
             */
            String name = "";
            for (int k = 0; k < subList.size(); k++) {
                name = name + subList.get(k).getName() + "；</br>";
            }
            list.get(i).setName(name);
        }
        return list;
    }

    /**
     * 款票审批列表  赵晨博
     *
     * @param model
     * @return
     */
    public List<InvoiceListModel> invoiceListModelList2(InvoiceListModel model) {
        if (model.getAppStatus() == 1) {
            List<InvoiceListModel> list = invoiceListDao.invoiceExamineList(model);
            int m = list.size();
            for (int i = 0; i < m; i++) {
                List<InvoiceListModel> subList = invoiceListDao.selectProjecByConId(list.get(i).getConId());
                /**
                 * 循环项目名称
                 */
                String name = "";
                for (int k = 0; k < subList.size(); k++) {
                    name = name + subList.get(k).getName() + "；</br>";
                }
                list.get(i).setName(name);
            }
            return list;
        } else if (model.getAppStatus() == 2) {
            List<InvoiceListModel> list = invoiceListDao.appedInvoiceExamineList(model);
            int m = list.size();
            for (int i = 0; i < m; i++) {
                List<InvoiceListModel> subList = invoiceListDao.selectProjecByConId(list.get(i).getConId());
                /**
                 * 循环项目名称
                 */
                String name = "";
                for (int k = 0; k < subList.size(); k++) {
                    name = name + subList.get(k).getName() + "；</br>";
                }
                list.get(i).setName(name);
            }
            return list;
        }
        return null;
    }


    /**
     * 款票提交列表  赵晨博
     *
     * @param model
     * @return
     */
    public List<InvoiceListModel> invoiceListModelList3(InvoiceListModel model) {
        List<InvoiceListModel> list = invoiceListDao.invoiceSumbitList(model);
        int m = list.size();
        for (int i = 0; i < m; i++) {
            List<InvoiceListModel> subList = invoiceListDao.selectProjecByConId(list.get(i).getConId());
            /**
             * 循环项目名称
             */
            String name = "";
            for (int k = 0; k < subList.size(); k++) {
                name = name + subList.get(k).getName() + "；</br>";
            }
            list.get(i).setName(name);
        }
        return list;
    }

    /**
     * 合同信息  赵晨博
     *
     * @param conId
     * @return
     */
    public InvoiceListModel contractInfo(Integer conId) {
        InvoiceListModel model = invoiceListDao.selectConstractInfoById(conId);//合同信息
//        List<InvoiceListModel> proList = invoiceListDao.invoiceList2(conId);//合同包含项目
        List<InvoiceListModel> pList = invoiceListDao.selectProjecByConId(conId);
        String name = "";
        for (int k = 0; k < pList.size(); k++) {
            name = name + pList.get(k).getName() + "；";
        }
        model.setName(name);
        return model;
    }


    /**
     * 合同的款项信息  赵晨博
     *
     * @param conId
     * @return
     */
    public List<InvoiceListModel> returnMoneyInfoByConId(Integer conId) {
        List<InvoiceListModel> model = invoiceListDao.selectReturnMoneyInfoByConId(conId);
        return model;
    }

    /**
     * 合同的总包款项信息  赵晨博
     *
     * @param conId
     * @return
     */
    public List<InvoiceListModel> returnZBMoneyInfoByConId(Integer conId) {
        List<InvoiceListModel> model = invoiceListDao.selectReturnZBMoneyInfoByConId(conId);
        return model;
    }


    /**
     * 合同的具体某个款项的信息   赵晨博
     *
     * @param conId
     * @param rmiMoneyType
     * @return
     */
    public InvoiceListModel rmInfoByConIdAndRmiMoneyType(Integer conId, Integer rmiMoneyType) {
        InvoiceListModel model = invoiceListDao.selectRmiByConIdAndRmiMoneyType(conId, rmiMoneyType);
        return model;
    }

    /**
     * 合同的具体某个款项的信息(总包)   赵晨博
     *
     * @param conId
     * @param rmiMoneyType
     * @return
     */
    public InvoiceListModel rmZBInfoByConIdAndRmiMoneyType(Integer conId, Integer rmiMoneyType) {
        InvoiceListModel model = invoiceListDao.selectZBRmiByConIdAndRmiMoneyType(conId, rmiMoneyType);
        return model;
    }


    /**
     * 修改款项信息(非总包)
     *
     * @param conId
     * @param rmiMoneyType
     * @param singleAlreadyMoney
     * @param singleRmiDebtsMoney
     * @param singleRmiBadMoney
     * @param rmiExpectDate
     * @return
     */
    public int updateRmInfo(Integer conId,
                            Integer rmiMoneyType,
                            BigDecimal singleAlreadyMoney,
                            BigDecimal singleRmiDebtsMoney,
                            BigDecimal singleRmiBadMoney,
                            Date rmiExpectDate) {
        int i = invoiceListDao.updateRmiInfoByConIdAndRmiMoneyType(conId, rmiMoneyType, singleAlreadyMoney, singleRmiDebtsMoney, singleRmiBadMoney, rmiExpectDate);
        return i;
    }

    /**
     * 修改款项信息(总包)
     *
     * @param conId
     * @param rmiMoneyType
     * @param singleAlreadyMoney
     * @param singleRmiDebtsMoney
     * @param singleRmiBadMoney
     * @param rmiExpectDate
     * @return
     */
    public int updateZBRmInfo(Integer conId,
                              Integer rmiMoneyType,
                              BigDecimal singleAlreadyMoney,
                              BigDecimal singleRmiDebtsMoney,
                              BigDecimal singleRmiBadMoney,
                              Date rmiExpectDate
    ) {
        int i = invoiceListDao.updateZBRmiInfoByConIdAndRmiMoneyType(conId, rmiMoneyType, singleAlreadyMoney, singleRmiDebtsMoney, singleRmiBadMoney, rmiExpectDate);
        return i;
    }


    /**
     * 查询合同列表
     *
     * @param conId
     * @return
     */
    public List<InvoiceListModel> InvInfoByConId(Integer conId) {
        List<InvoiceListModel> model = invoiceListDao.selectInvInfoByConId(conId);
        return model;
    }


    /**
     * 上传文件
     *
     * @param file
     * @param invId 发票id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int uploadFile(MultipartFile[] file, Integer invId, String remark) {
        InvoiceListModel model = invoiceListDao.selectFPByInvId(invId);
        User user = ShiroUtils.getUser();
        if (null != file && file.length > 0) {
            for (MultipartFile f : file) {
                String path = uploadPath + "invoice/" + invId + "/";
                String fileName = FileUtils.upload(f, path);
                if (StringUtils.isNotNull(fileName)) {
                    String url = "/files/invoice/" + invId + "/" + fileName;
                    FileModel fileModel = new FileModel();
                    fileModel.setMainId(invId);
                    fileModel.setFileName(fileName);
                    fileModel.setFileComment(remark);
                    fileModel.setFileType(6);
                    fileModel.setFileUrl(url);
                    fileModel.setUserId(user.getAccount());
                    fileModel.setUserName(user.getName());
                    fileModel.setFileStatus(1);
                    fileModel.setFilePath(path);
                    logService.saveLog("上传发票附件", "发票号：" + model.getInvCode());
                    return fileDao.addFileInfo(fileModel);
                }
            }
        }
        return 0;
    }


    /**
     * 查询发票附件列表
     *
     * @param invId
     * @return
     */
    public List<FileModel> FileList(Integer invId) {
        List<FileModel> model = invoiceListDao.selectFileListByInvId(invId);
        return model;
    }


    /**
     * 下载附件
     *
     * @param fileId
     * @param response
     * @return
     */
    public String DownLoad(Integer fileId, HttpServletResponse response) {
        FileModel model = fileDao.selFileInfoById(fileId);
        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(model.getFilePath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(model.getFileName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return "下载失败";
        }
        return "下载成功";
    }

    /**
     * 删除附件
     *
     * @param fileId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String deleteAnnexByFileId(Integer fileId, String invCode) {
        String result = null;
        int i = fileDao.delFileInfo(fileId);
        if (i == 1) {
            logService.saveLog("删除发票附件", "发票号：" + invCode);
            result = "删除成功";
            return result;
        }
        result = "删除失败";
        return result;
    }

    /**
     * 删除发票
     *
     * @param invId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String deleteInvoiceByInvId(Integer invId) {
        String result = "";
        InvoiceListModel model = invoiceListDao.selectFPByInvId(invId);
        int i = invoiceListDao.deleteInvoiceByInvId(invId);
        logService.saveLog("删除发票信息", "发票号：" + model.getInvCode());
        if (i == 1) {
            result = "删除成功";
            return result;
        }
        result = "删除失败";
        return result;
    }


    /**
     * 添加发票及附件
     *
     * @param invConId
     * @param invCode
     * @param invGoodsName
     * @param invAmount
     * @param invDate
     * @param file
     * @param remark
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String addInvoice(Integer invConId,
                             String invCode,
                             String invGoodsName,
                             BigDecimal invAmount,
                             Date invDate,
                             MultipartFile[] file,
                             String remark) {
        User user = ShiroUtils.getUser();
        InvoiceInfo info = new InvoiceInfo();
        info.setInvConId(invConId);
        info.setInvCode(invCode);
        info.setInvGoodsName(invGoodsName);
        if(invAmount == null){
            invAmount = BigDecimal.valueOf(0);
        }else{
            info.setInvAmount(invAmount);
        }
        info.setInvCreateDate(new Date());
        info.setInvDate(invDate);
        info.setInvTakePerson(user.getName());
        String msg = "";
        int a = invoiceListDao.selectAlreadySumAmount(invConId);//已收发票金额
        int b = invoiceListDao.selectSumys(invConId);//应收总额
        int c = invAmount.intValue();
        if (b < a + c) {
            msg = "添加失败";
            return msg;
        }
        int i = invoiceListDao.addInvoice(info);
        InvoiceListModel model2 = invoiceListDao.selectContractByConId(invConId);
        int k = info.getInvId();
        int j = uploadFile(file, k, remark);
        if (j == -1) {
            msg = "添加失败";
            return msg;
        } else {
            InvoiceListModel model3 = invoiceListDao.selectConByConId(invConId);
            logService.saveLog("添加发票", "项目编号：" + model3.getContName()
                    + " ；发票号：" + invCode + " ；发票金额：" + invAmount);
            msg = "添加成功";
            return msg;
        }
    }


    /**
     * 提交审核
     *
     * @param conId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int kpAppInfo(Integer conId) {
        int flg = 1;
        try {
            //首先修改合同的状态
            InvoiceListModel model = new InvoiceListModel();
            model.setConId(conId);
            /**
             * 0 未完成 1保存未提交 2提交未审核  3 被驳回 4已完结
             */
            model.setMoneyInvoiceStatue(2);
            invoiceListDao.updkpStatus(model);

            //单据表增加审核和合同的关系
            InvoiceListModel model_sheet = new InvoiceListModel();
            model_sheet.setBllId(conId);
            User user = ShiroUtils.getUser();
            model_sheet.setSubmitUser(user.getId());
            /**
             * 1预算审核2报价审核3合同审核4款票审核6核算审核7概算审核
             */
            model_sheet.setAppType(4);//款票
            invoiceListDao.addSheetDetail(model_sheet);

            //生成下一步待审核的记录************************
            //01 首先需要查询对应的流程信息
            InvoiceListModel addAppInfo = new InvoiceListModel();
            /**
             * 执行成功以后，获取数据的主键
             */
            int i = model_sheet.getId();
            addAppInfo.setSheetId(model_sheet.getId());
            addAppInfo.setVCode("KP001");
            /**
             * 0=被驳回，1=未审核，2=已审核
             */
            addAppInfo.setAppStatus(1);

            //循环判断 当前的账号所在的流程节点；
            List<InvoiceListModel> nowUserNodeInfo = invoiceListDao.selAppNodeInfoByUserId(user.getId());
            //分2种情况
            if (nowUserNodeInfo == null || nowUserNodeInfo.size() == 0) {
                //无数据；1·没有再审批节点中，是员工级别的，那么直接就按照流程顺序走。
                List<InvoiceListModel> appList = invoiceListDao.selAppNodeInfo(0);
                // 然后在找下一个节点和下下节点。

                /**
                 * 上一个节点是0
                 */
                addAppInfo.setComp(0);

                /**
                 * 判断流程节点，是1个还是2个及以上。
                 */
                if (appList != null && appList.size() == 1) {
                    //获取第一条数据，为当前的节点号，执行人。
                    //获取第二条数据的，节点。
                    addAppInfo.setNowNode(appList.get(0).getId());
                    addAppInfo.setOrderNo(appList.get(0).getOrderNo());
                    addAppInfo.setStart(0);
                    /**
                     * 根据我当前登录的账号，和流程配置的级别，找到那个人、
                     */
                    int pid = invoiceListDao.selNowLevelByUserId(user.getId());
                    /**
                     * 执行递归查询
                     */
                    addAppInfo.setVerifier(getPid(appList.get(0).getPost(), pid));

                } else if (appList != null && appList.size() >= 2) {
                    addAppInfo.setNowNode(appList.get(0).getId());
                    addAppInfo.setOrderNo(appList.get(0).getOrderNo());
                    /**
                     * 根据我当前登录的账号，和流程配置的级别，找到那个人、
                     */
                    int pid = invoiceListDao.selNowLevelByUserId(user.getId());
                    /**
                     * 执行递归查询
                     */
                    addAppInfo.setVerifier(getPid(appList.get(0).getPost(), pid));
                    addAppInfo.setStart(appList.get(1).getId());
                }

                // 然后判断下一个节点和下下节点是不是最后一个节点
            } else {
                //有数据；2·在流程的中间，那么返回它的，顺序、是否为起点、是否为终点。
                List<InvoiceListModel> appList2 = invoiceListDao.selAppNodeInfo(nowUserNodeInfo.get(0).getOrderNo());

                /**
                 * 上一步，一定是0 ，因为我是申请啊。
                 */
                addAppInfo.setComp(0);
                /**
                 * 下一步，是流程的下一步
                 */
                addAppInfo.setStart(nowUserNodeInfo.get(0).getId());
                addAppInfo.setNowNode(appList2.get(0).getId());
                addAppInfo.setOrderNo(appList2.get(0).getOrderNo());

                int pid = invoiceListDao.selNowLevelByUserId(user.getId());
                /**
                 * 执行递归查询
                 */
                addAppInfo.setVerifier(getPid(appList2.get(0).getPost(), pid));
            }
            invoiceListDao.addVerifyProcess(addAppInfo);

        } catch (Exception ex) {
            flg = -1;
        }

        logService.saveLog("提交款票审核", "项目编号：" + invoiceListDao.selectContractByConId(conId).getContName());
        return flg;
    }

    /**
     * 递归：直到找到审批级别的上级人员id为止
     *
     * @param post
     * @param pid
     * @return
     */
    private int getPid(int post, int pid) {
        int userId = 0;
        InvoiceListModel nextModel = invoiceListDao.selNextLevelUserByPId(pid);
        if (nextModel != null) {
            if (nextModel.getPost() == post) {
                userId = nextModel.getSubmitUser();
            } else {
                getPid(post, nextModel.getParentId());
            }
        }
        return userId;
    }

    /**
     * 待审批列表
     *
     * @param model
     * @return
     */
//    public List<ConContractMainModel> unAppContractList(ConContractMainModel model) {
//        List<ConContractMainModel> list = conContractMainDao.unAppContractList(model);
//        User user = ShiroUtils.getUser();
//
//        int m = list.size();
//        for (int i = 0; i < m; i++) {
//            ContractModel model1 = new ContractModel();
//            List<ContractModel> subList = contractDao.selectProjectById(list.get(i).getFkId());
//            /**
//             * 循环项目名称
//             */
//            String name = "";
//            for (int k = 0; k < subList.size(); k++) {
//                name = name + subList.get(k).getName() + "；</br>";
//            }
//            list.get(i).setProjectName(name);
//            list.get(i).setLoginUid(user.getId());
//        }
//        return list;
//    }


    /**
     * 根据id 处理审批
     *
     * @param model
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int approveKpInfoByBllId(InvoiceListModel model) {
        int flg = 1;
        //当前的数据id
        //appStatus 审批状态 0 ng 2 ok
        //remark 审批意见
        try {
            invoiceListDao.updVerifyProcess(model);
            //根据当前的节点，OK NG+意见
            //1·OK
            InvoiceListModel nowProcess = invoiceListDao.selectVerifyProcess(model.getId());
            //循环判断 当前的账号所在的流程节点；
            User user = ShiroUtils.getUser();
            List<InvoiceListModel> nowUserNodeInfo = invoiceListDao.selAppNodeInfoByUserId(user.getId());
            /**
             * 审批状态为2时；代表通过
             */
            if (model.getAppStatus() == 2) {
                /**
                 * 下一个节点=0 就是当前是最后的节点了，需要修改业务主表的状态值
                 */
                if (nowProcess.getStart() == 0) {
                    //1.1·当前是否是最后一个节点
                    //1.1.1·修改业务主表的状态值

                    /**
                     * con_contract_main money_invoice_statue:0 未完成 1保存未提交 2提交未审核 3被驳回 4已完结
                     */
                    model.setMoneyInvoiceStatue(4);
                    invoiceListDao.updContractKPStatuse(model);
                    /**
                     * 同时修改任务对应的合同的进度；
                     */
                    model.setEndDate(new Date());
                    model.setTstatus(3);
                    int i = invoiceListDao.updateKpTask(model);
                    logService.saveLog("审核款票信息", "项目编号：" + invoiceListDao.selectConByConId(model.getConId()).getContName() + " 审核通过");
                } else {
                    //1.2·找到下一个节点、下下个节点、审批人
                    List<InvoiceListModel> appList = invoiceListDao.selAppNodeInfo(nowUserNodeInfo.get(0).getOrderNo());
                    /**
                     * 根据我当前登录的账号，和流程配置的级别，找到那个人、
                     */
                    InvoiceListModel addAppInfo = new InvoiceListModel();

                    int pid = invoiceListDao.selNowLevelByUserId(user.getId());
                    /**
                     * 执行递归查询
                     */
                    addAppInfo.setVerifier(getPid(appList.get(0).getPost(), pid));
                    addAppInfo.setNowNode(appList.get(0).getId());
                    addAppInfo.setOrderNo(appList.get(0).getOrderNo());

                    if (appList != null && appList.size() >= 2) {
                        addAppInfo.setStart(appList.get(1).getId());
                    } else {
                        addAppInfo.setStart(0);
                    }
                    //下一个节点的，上一个节点是现在的id
                    addAppInfo.setComp(nowProcess.getNowNode());
                    addAppInfo.setVCode("KP001");
                    addAppInfo.setSheetId(nowProcess.getSheetId());
                    addAppInfo.setAppStatus(1);
                    invoiceListDao.addVerifyProcess(addAppInfo);
                    logService.saveLog("审核款票信息", "项目编号：" + invoiceListDao.selectConByConId(model.getConId()).getContName() + " 审核通过");

                }
            } else {
                //2·NG+意见
                //2.1·存储当前的状态+结果
                if (nowProcess.getComp() == 0) {
                    //2.2.1·如果上一个是提交的话，修改业务主表的状态值
                    /**
                     * con_contract_main money_invoice_statue:0 未完成 1保存未提交 2提交未审核 3被驳回 4已完结
                     */
                    model.setMoneyInvoiceStatue(3);
                    invoiceListDao.updContractKPStatuse(model);
                    logService.saveLog("审核款票信息", "项目编号：" + invoiceListDao.selectConByConId(model.getConId()).getContName() + " 驳回");
                } else {
                    //2.2·找到上一个节点，生成下一个节点、审批人//
                    /**
                     * 根据我当前审批记录，找到我上一个临近的、
                     */
                    InvoiceListModel addAppInfo = invoiceListDao.selNextUserByNgInfo(model.getId());
                    addAppInfo.setAppStatus(1);
                    invoiceListDao.addVerifyProcess(addAppInfo);
                    logService.saveLog("审核款票信息", "项目编号：" + invoiceListDao.selectConByConId(model.getConId()).getContName() + " 驳回");
                }
            }
        } catch (Exception ex) {
            flg = -1;
        }
        return flg;
    }


    /**
     * 修改款票状态为  保存未提交 1    任务表 开始时间 执行人
     *
     * @param conId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateKpStatus(Integer conId) {
        InvoiceListModel invoiceListModel = new InvoiceListModel();
        User user = ShiroUtils.getUser();
        invoiceListModel.setConId(conId);
        invoiceListModel.setTstatus(2);
        invoiceListModel.setBeginDate(new Date());
        invoiceListModel.setKeyPerson(user.getAccount());
        invoiceListModel.setKeyPersonId(user.getId());
        invoiceListDao.beginKpTask(invoiceListModel);
        InvoiceListModel model = invoiceListDao.selectConByConId(conId);
        logService.saveLog("保存款票信息", "项目编号：" + model.getContName());
        return invoiceListDao.upkpStatusByConId(conId);
    }


    /**
     * 款票审批过程
     *
     * @param conId
     * @return
     */
    public List<InvoiceListModel> selectAppProcessByConId(int conId) {
        return invoiceListDao.selectAppProcessByConId(conId);
    }

    /**
     * 更新款票任务
     *
     * @param invoiceListModel
     */
    public int updateKpTask(InvoiceListModel invoiceListModel) {
        return invoiceListDao.updateKpTask(invoiceListModel);
    }


    /**
     * 编辑 发票    update
     *
     * @param invId
     * @param invCode
     * @param invGoodsName
     * @param invAmount
     * @param invDate
     * @param file
     * @param remark
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String InvoiceUpdate(Integer invConId, Integer invId, String invCode, String invGoodsName, BigDecimal invAmount, Date invDate, MultipartFile[] file, String remark) {
        int a = invoiceListDao.selectAlreadySumAmount(invConId);//已收发票金额
        int b = invoiceListDao.selectSumys(invConId);//应收总额
        BigDecimal c = invoiceListDao.selectAmountByInvId(invId);//当前invId 发票的原金额
        int i = 0;
        if (a + invAmount.doubleValue() - c.intValue() <= b) {
            i = invoiceListDao.updateInvoiceByInvId(invId, invCode, invGoodsName, invAmount.setScale(2, BigDecimal.ROUND_HALF_UP), invDate);
            logService.saveLog("修改发票信息", "发票号：" + invCode);
        }
        if (i == 1) {
            return "修改成功";
        }
        return "修改失败";
    }

    /**
     * 查询合同信息  select *
     *
     * @param conId
     * @return
     */
    public InvoiceListModel selectContractByConId(Integer conId) {
        return invoiceListDao.selectContractByConId(conId);
    }

    /**
     * 添加合同表 回款编辑人
     */
    public void addEditUser(String keditUserName, Integer conId) {
        invoiceListDao.addEditUser(keditUserName, conId);
    }


    /**
     * 比较double类型数值大小  返回true相等
     *
     * @param a
     * @param b
     * @return
     */
    public boolean equalDouble(double a, double b) {
        if ((a - b > -0.000001) && (a - b) < 0.000001)
            return true;
        else
            return false;
    }

    /**
     * 新   回款编辑（非总包  +  总包）
     *
     * @param model
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveUpdateMoney(InvoiceListModel model) {
        Double yishou;
        Double mozhang;
        Double huaizhang;
        Date riqi;
        if (model.getRmiActualMoney() == null) {
            yishou = 0.0;
        } else {
            yishou = model.getRmiActualMoney().doubleValue();
        }

        if (model.getSingleRmiDebtsMoney() == null) {
            mozhang = 0.0;
        } else {
            mozhang = model.getSingleRmiDebtsMoney().doubleValue();
        }

        if (model.getSingleRmiBadMoney() == null) {
            huaizhang = 0.0;
        } else {
            huaizhang = model.getSingleRmiBadMoney().doubleValue();
        }

        if (model.getRmiExpectDate() == null) {
            model.setRmiExpectDate(new Date(" Jan 01 00:00:00 CST 1900"));
        }
        riqi = model.getRmiExpectDate();


        //查询原回款信息
        InvoiceListModel Ymodel;
        String str = "";
        String moneyType = "";
        if (model.getRmiIsAll() == 0) {//非总包
            Ymodel = invoiceListDao.selectRmiByConIdAndRmiMoneyType(model.getConId(), model.getRmiMoneyType());
        } else {//总包
            Ymodel = invoiceListDao.selectZBRmiByConIdAndRmiMoneyType(model.getConId(), model.getRmiMoneyType());
            str = "总包";
        }
        switch (model.getRmiMoneyType()) {
            case 1:
                moneyType = "预付款";
                break;
            case 2:
                moneyType = "进度款";
                break;
            case 3:
                moneyType = "发货款";
                break;
            case 4:
                moneyType = "到货款";
                break;
            case 5:
                moneyType = "调试款";
                break;
            case 6:
                moneyType = "验收款";
                break;
            case 7:
                moneyType = "质保金";
                break;
            case 8:
                moneyType = "提货款";
                break;
            case 9:
                moneyType = "完工款";
                break;
            case 10:
                moneyType = "全款";
                break;

        }
        Double Yyishou;
        Double Ymozhang;
        Double Yhuaizhang;
        if (Ymodel.getRmiActualMoney() == null) {
            Yyishou = 0.0;
        } else {
            Yyishou = Ymodel.getRmiActualMoney().doubleValue();
        }
        if (Ymodel.getSingleRmiDebtsMoney() == null) {
            Ymozhang = 0.0;
        } else {
            Ymozhang = Ymodel.getSingleRmiDebtsMoney().doubleValue();
        }
        if (Ymodel.getSingleRmiBadMoney() == null) {
            Yhuaizhang = 0.0;
        } else {
            Yhuaizhang = Ymodel.getSingleRmiBadMoney().doubleValue();
        }
        Double expectMoney = Ymodel.getSingleRmiExpectMoney().doubleValue();//应收总额
        Date Ydate = Ymodel.getRmiExpectDate();

        //判断修改项
        InvoiceListModel model2 = invoiceListDao.selectConByConId(model.getConId());

        if (yishou + mozhang + huaizhang <= expectMoney && (!equalDouble(yishou, Yyishou) || !equalDouble(mozhang, Ymozhang) || !equalDouble(huaizhang, Yhuaizhang) || riqi != Ydate || riqi == Ydate)) {
            //1.只更改 已收
            if (!equalDouble(yishou, Yyishou) && equalDouble(mozhang, Ymozhang) && equalDouble(huaizhang, Yhuaizhang)) {
                if (yishou + Ymozhang + Yhuaizhang <= expectMoney) {// 新已收 + 原抹账 + 原坏账 <= 应收总额
                    model.setRmiActualMoney(BigDecimal.valueOf(yishou)); //model 更改 新已收值
                    logService.saveLog("修改" + str + moneyType + "回款信息", "项目编号：" + model2.getContName() +
                            " ;原已收金额：" + Yyishou + " ;修改为：" + yishou);
                }
            }
            //2.只修改抹账
            if (equalDouble(yishou, Yyishou) && !equalDouble(mozhang, Ymozhang) && equalDouble(huaizhang, Yhuaizhang)) {
                if (Yyishou + mozhang + Yhuaizhang <= expectMoney) { //原已收 + 新抹账 + 原坏账 <= 应收总额
                    model.setRmiDebtsMoney(BigDecimal.valueOf(mozhang));//model 更改 新抹账值
                    logService.saveLog("修改" + str + moneyType + "回款信息", "项目编号：" + model2.getContName() +
                            " ;原抹账金额：" + Ymozhang + " ;修改为：" + mozhang);
                }
            }
            //3.只修改坏账
            if (equalDouble(yishou, Yyishou) && equalDouble(mozhang, Ymozhang) && !equalDouble(huaizhang, Yhuaizhang)) {
                if (Yyishou + Ymozhang + huaizhang <= expectMoney) {//原已收 + 原抹账 + 新坏账 <= 应收总额
                    model.setRmiBadMoney(BigDecimal.valueOf(huaizhang));//model 更改 新坏账值
                    logService.saveLog("修改" + str + moneyType + "回款信息", "项目编号：" + model2.getContName() +
                            " ;原坏账金额：" + Yhuaizhang + " ;修改为：" + huaizhang);
                }
            }
            //4.修改 已收 + 抹账
            if (!equalDouble(yishou, Yyishou) && !equalDouble(mozhang, Ymozhang) && equalDouble(huaizhang, Yhuaizhang)) {
                if (yishou + mozhang + Yhuaizhang <= expectMoney) {//新已收 + 新抹账+ 原坏账 <= 应收总额
                    model.setRmiActualMoney(BigDecimal.valueOf(yishou)); //model 更改 新已收值
                    model.setRmiDebtsMoney(BigDecimal.valueOf(mozhang));//model 更改 新抹账值
                    logService.saveLog("修改" + str + moneyType + "回款信息", "项目编号：" + model2.getContName() +
                            " ;原已收金额：" + Yyishou + " ;修改为：" + yishou + " ;原抹账金额：" + Ymozhang + " ;修改为：" + mozhang);
                }
            }
            //5.修改 已收 + 坏账
            if (!equalDouble(yishou, Yyishou) && equalDouble(mozhang, Ymozhang) && !equalDouble(huaizhang, Yhuaizhang)) {
                if (yishou + Ymozhang + huaizhang <= expectMoney) {//新已收 + 原抹账+ 新坏账 <= 应收总额
                    model.setRmiActualMoney(BigDecimal.valueOf(yishou)); //model 更改 新已收值
                    model.setRmiBadMoney(BigDecimal.valueOf(huaizhang));//model 更改 新坏账值
                    logService.saveLog("修改" + str + moneyType + "回款信息", "项目编号：" + model2.getContName() +
                            " ;原已收金额：" + Yyishou + " ;修改为：" + yishou + " ;原坏账金额：" + Yhuaizhang + " ;修改为：" + huaizhang);
                }
            }
            //6.修改 抹账 + 坏账
            if (equalDouble(yishou, Yyishou) && !equalDouble(mozhang, Ymozhang) && !equalDouble(huaizhang, Yhuaizhang)) {
                if (Yyishou + mozhang + huaizhang <= expectMoney) {//原已收 + 新抹账+ 新坏账 <= 应收总额
                    model.setRmiDebtsMoney(BigDecimal.valueOf(mozhang)); //model 更改 新抹账值
                    model.setRmiBadMoney(BigDecimal.valueOf(huaizhang));//model 更改 新坏账值
                    logService.saveLog("修改" + str + moneyType + "回款信息", "项目编号：" + model2.getContName() +
                            " ;原抹账金额：" + Ymozhang + " ;修改为：" + mozhang + " ;原坏账金额：" + Yhuaizhang + " ;修改为：" + huaizhang);
                }
            }
            //7.修改 已收 + 抹账 + 坏账
            if (!equalDouble(yishou, Yyishou) && !equalDouble(mozhang, Ymozhang) && !equalDouble(huaizhang, Yhuaizhang)) {
                if (yishou + mozhang + huaizhang <= expectMoney) {//新已收 + 新抹账+ 新坏账 <= 应收总额
                    model.setRmiActualMoney(BigDecimal.valueOf(yishou)); //model 更改 新已收值
                    model.setRmiDebtsMoney(BigDecimal.valueOf(mozhang)); //model 更改 新抹账值
                    model.setRmiBadMoney(BigDecimal.valueOf(huaizhang));//model 更改 新坏账值
                    logService.saveLog("修改" + str + moneyType + "回款信息", "项目编号：" + model2.getContName() +
                            " ;原已收金额：" + Yyishou + " ;修改为：" + yishou + " ;原抹账金额：" + Ymozhang + " ;修改为：" + mozhang +
                            " ;原坏账金额：" + Yhuaizhang + " ;修改为：" + huaizhang);
                }
            }
            return invoiceListDao.saveUpdateMoney(model);
        }
        return 0;
    }

    public List<InvoiceListModel> selAppList(Integer conId) {
        return invoiceListDao.selAppList(conId);
    }

    public int selectUserLevel(int loginUid) {
        return invoiceListDao.selectUserLevelByUserId(loginUid);
    }

    public List<InvoiceListModel> selectLikeTest(String sellCode) {
        return invoiceListDao.selectLikeTest(sellCode);
    }
}



